import os.path
import time
import threading
import logging
from libs.comps.common.component import manager , TComponentManager , TComponent
import paho.mqtt.client as mqtt

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class TCompMqClient(TComponent):
    def __init__(self, _manager):
        super().__init__(_manager)
        self._client :mqtt.Client = None
        self.clientId = ""
        self.subTopics =[]
        self._last_connect_time = 0
        self._stop_event = threading.Event
    @property
    def client (self):
        try:
            if self._client == None:
                self.clientId = self.clientId if self.clientId!="" else 'mq-'+str(int(1000*time.time()))
                client = mqtt.Client(  client_id=self.clientId)
                uid = self.compSettings['uid']
                pwd = self.compSettings['pwd']
                client.username_pw_set(username=uid , password=pwd)
                self._client = client
                self._client.on_connect = self.on_connect
                self._client.on_disconnect = self.on_disconnect
                self._client.on_message = self.on_message
        except Exception as er:
            self.manager.log(self , er)
        return self._client
    @property
    def force_reconnect_interval(self):
        return self.compSettings['force_reconnect_interval'] if "force_reconnect_interval" in self.compSettings.keys() else 300
    @property
    def reconnect_delay_min(self):
        return self.compSettings['reconnect_delay_min'] if "reconnect_delay_min" in self.compSettings.keys() else 2

    def on_connect(self, client, userdata, flags, reason_code, properties):
        if reason_code == 0:
            logger.info("✅ 成功连接到 MQTT 服务器")
            for topic in self.subTopics:
                client.subscribe(topic)
            logger.info(f"📡 已订阅主题: {topic}")
            self.reconnect_delay = self.reconnect_delay_min
            self._last_connect_time = time.time()
        else:
            logger.error(f"❌ 连接失败，返回码: {reason_code}")
    def on_disconnect(self, client, userdata, disconnect_flags, reason_code, properties):
        logger.warning("⚠️ 与 MQTT 服务器断开连接")
        if not self._stop_event.is_set():
            self._reconnect_loop()
    def on_message(self, client, userdata, msg):
        try:
            self.onMessage(msg , self )
        except Exception as er:
            self.manager.log(self , er)
    def _force_reconnect_if_needed(self):
        """每小时强制重连一次"""
        while not self._stop_event.is_set():
            if (self._last_connect_time and time.time() - self._last_connect_time >= self.force_reconnect_interval):
                logger.info("⏰ 到达定时重连时间，正在主动断开连接...")
                self.client.disconnect()  # 触发 on_disconnect，进而触发重连
                # 等待一段时间确保断开完成（可选）
                time.sleep(2)
            time.sleep(10)  # 每10秒检查一次
    def start(self):
        try:
            logger.info("🚀 启动 MQTT 客户端...")
            broker = self.compSettings['host']
            port = self.compSettings['port']
            self.client.connect(broker, port, keepalive=60)
            self.client.loop_start()  # 启动后台网络循环（非阻塞）

            # 启动定时强制重连线程
            timer_thread = threading.Thread(target=self._force_reconnect_if_needed, daemon=True)
            timer_thread.start()

            # 主线程等待中断
            while not self._stop_event.is_set():
                time.sleep(1)
        except Exception as er:
            self.manager.log(self , er)
    def stop(self):
        self._stop_event.set()
        self.client.loop_stop()
        self.client.disconnect()
        logger.info("🔌 MQTT 客户端已停止")
    def onMessage(self, message, mqttClient):
        try:
            pass
        except Exception as er:
            self.manager(self, er)

